import { listApprovalAsk, pageReleaseReceipt, selectNeeds } from '@/services/api/api-needs';
import { DownloadOutlined, UserOutlined } from '@ant-design/icons';
import { ActionType, ProList } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import {
  Alert,
  Avatar,
  Button,
  Card,
  Col,
  Descriptions,
  Divider,
  Flex,
  Image,
  Row,
  Space,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import Meta from 'antd/es/card/Meta';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddApproval from './AddApproval';
import AddAsk from './AddAsk';
import AddReceiptReply from './AddReceiptReply';
import AddRelease from './AddRelease';
import EditNeeds from './EditNeeds';
import ReceiptNeeds from './ReceiptNeeds';
interface DetailsNeedsProps {
  id: string;
  name: string;
  onRefurbish: () => void;
  submitId: string;
}

const DetailsNeeds: React.FC<DetailsNeedsProps> = ({ id, name, onRefurbish, submitId }) => {
  const access = useAccess();

  const [details, setDetailsState] = useState<NeedsData.NeedsDetails>();

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);
  const [drawerFormVisible, setDrawerFormVisible] = useState(false);
  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  useEffect(() => {
    if (submitId === id) {
      if (submitId !== undefined) {
        setDrawerFormVisible(true);
      }
    }
  }, []);

  const iframeRef = useRef(null);

  const handleLoad = () => {
    console.log('加载完成');
    setPreviewLoading(false);
  };

  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener('load', handleLoad);
    return () => {
      iframe?.removeEventListener('load', handleLoad);
    };
  }, [previewOnlineUrl]);

  /**
   * 获取 详情
   * @param key
   */
  const loadDetails = async () => {
    try {
      const response = await selectNeeds({ id });
      if (response.code === 0) {
        setDetailsState(response.data);
      }
    } catch (error) {}
  };

  const [openAddActive, setOpenAddActive] = useState<boolean>();

  const [approvals, setApprovalsState] = useState<NeedsData.Approval[]>();

  /**
   * 加载 请示 列表
   */
  const loadListApprovalAsk = async () => {
    try {
      const response = await listApprovalAsk({
        interviewId: id,
      });
      if (response.code === 0) {
        setApprovalsState(response.data);
      }
    } catch (error) {}
  };

  const actionRef = useRef<ActionType>();

  return (
    <DrawerForm
      key="details_details_drawer_form"
      title={
        <Space>
          <span>详情</span>
          <Tag color="green">{details?.isRelease == 0 ? '未发布' : '已发布'}</Tag>
        </Space>
      }
      drawerProps={{
        // maskClosable: false,
        destroyOnClose: true,
        width: 1000,
      }}
      trigger={<a>{name}</a>}
      open={drawerFormVisible}
      onOpenChange={(visible) => {
        if (visible) {
          loadDetails();
          if (access.媒体采访x配置x管理员) {
            loadListApprovalAsk();
          }
        } else {
          onRefurbish();
        }
        setDrawerFormVisible(visible);
      }}
      submitter={
        (access.媒体采访x配置x管理员 || access.媒体采访x配置x接收者) && {
          render: (props, defaultDoms) => {
            if (access.媒体采访x配置x管理员) {
              return [
                details?.isRelease == 0 && (
                  <EditNeeds
                    data={details}
                    onRefurbish={function (): void {
                      loadDetails();
                      loadListApprovalAsk();
                    }}
                  />
                ),
                details?.isRelease == 0 && (
                  <AddAsk
                    interviewId={id}
                    onRefurbish={function (): void {
                      loadDetails();
                      loadListApprovalAsk();
                    }}
                  />
                ),
                details?.isRelease == 0 && (
                  <AddRelease
                    interviewId={id}
                    onRefurbish={function (): void {
                      loadDetails();
                      loadListApprovalAsk();
                    }}
                  />
                ),

                // details?.isRelease == 0 && (
                //   <EditNeedsRelease
                //     data={details}
                //     onRefurbish={function (): void {
                //       loadDetails();
                //       loadListApprovalAsk();
                //     }}
                //   />
                // ),
              ];
            } else {
              return [
                details?.isRelease == 1 && (
                  <AddReceiptReply
                    interviewId={id}
                    onRefurbish={function (): void {
                      loadDetails();
                    }}
                  />
                ),
              ];
            }
          },
        }
      }
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={details === undefined}
      >
        <Row>
          <Col span={access.媒体采访x配置x管理员 ? 15 : 24}>
            {details !== undefined && (
              <>
                <Descriptions>
                  <Descriptions.Item label="创建单位">
                    {details.createdOrganizationName}
                  </Descriptions.Item>
                  <Descriptions.Item label="创建人">{details.createdAccountName}</Descriptions.Item>
                  <Descriptions.Item label="创建时间">
                    {dayjs(details.createdTime).format('YYYY-MM-DD')}
                  </Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item span={3} label="联络方式">
                    <Space size={[8, 16]} wrap>
                      {details.contacts &&
                        details.contacts.map((item) => (
                          <Card
                            style={{ width: 150 }}
                            bodyStyle={{
                              paddingTop: '10px',
                              paddingBottom: '10px',
                            }}
                          >
                            <Meta
                              title={
                                <>
                                  <Tag style={{ marginRight: 5 }}>{item.name}</Tag>
                                </>
                              }
                              description={item.phone}
                            />
                          </Card>
                        ))}
                    </Space>
                  </Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item span={3} label="审批意见">
                    <Space size={[8, 16]} wrap>
                      {details.managers &&
                        details.managers.map((item) => (
                          <Card
                            style={{ width: access.媒体采访x配置x管理员 ? 500 : 350 }}
                            bodyStyle={{
                              paddingTop: '10px',
                              paddingBottom: '10px',
                            }}
                          >
                            <Meta
                              title={
                                <>
                                  <Tag style={{ marginRight: 5 }}>{item.name}</Tag>
                                  <Tag style={{}}>{item.position}</Tag>
                                </>
                              }
                              description={item.instructions}
                            />
                          </Card>
                        ))}
                    </Space>
                  </Descriptions.Item>
                </Descriptions>
                <Divider
                  orientation="left"
                  style={{
                    fontSize: 14,
                    fontWeight: 'bold',
                  }}
                >
                  采访需求
                </Divider>
                <Descriptions>
                  <Descriptions.Item label="发起单位">
                    {details.initiateOrganization}
                  </Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item label="采访主题">{details.name}</Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item label="采访主体">
                    <Space wrap>
                      {details.interviewees &&
                        details.interviewees.map((item) => <Tag>{item}</Tag>)}
                    </Space>
                  </Descriptions.Item>
                </Descriptions>
                <Descriptions column={1}>
                  <Descriptions.Item label="采访媒体">
                    <div style={{ width: '100%', marginTop: '-16px' }}>
                      {details.assignOrganizationTree &&
                        details.assignOrganizationTree.map((item) =>
                          item.children != undefined ? (
                            <div>
                              <Divider
                                orientation="left"
                                style={{
                                  fontSize: 14,
                                }}
                              >
                                <Tag color={'red'}>{item.name}</Tag>
                              </Divider>
                              <Space wrap>
                                {item?.children.map((child) => (
                                  <Tag>{child.name}</Tag>
                                ))}
                              </Space>
                            </div>
                          ) : (
                            <></>
                          ),
                        )}
                    </div>
                  </Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item label="采访时间">
                    <Space>
                      {dayjs(details.interviewTimes[0]).format('YYYY-MM-DD')}
                      <span>-</span>
                      {dayjs(details.interviewTimes[1]).format('YYYY-MM-DD')}
                    </Space>
                  </Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item label="采访地点">{details.location}</Descriptions.Item>
                </Descriptions>
                <Divider
                  orientation="left"
                  style={{
                    fontSize: 14,
                    fontWeight: 'bold',
                  }}
                >
                  采访内容
                </Divider>
                {details?.content ? (
                  <div
                    dangerouslySetInnerHTML={{
                      __html: `${details?.content}`,
                    }}
                  />
                ) : (
                  <>暂无内容</>
                )}
                {details?.attachments && details?.attachments.length > 0 && (
                  <>
                    <Divider />
                    <div
                      style={{
                        textAlign: 'right',
                      }}
                    >
                      <Button
                        type="primary"
                        key="import"
                        size="small"
                        icon={<DownloadOutlined />}
                        onClick={() => {
                          details?.attachments.forEach(function (item) {
                            window.open(item.content, '_blank');
                          });
                        }}
                      >
                        全部下载
                      </Button>
                    </div>

                    <Upload
                      listType="picture"
                      multiple
                      fileList={details?.attachments.map((item) => {
                        return {
                          uid: item.id,
                          name: item.name,
                          url: item.content,
                          mimeType: item.mimeType,
                          status: 'done',
                        };
                      })}
                      showUploadList={{
                        downloadIcon: (
                          <div
                            style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}
                          >
                            <DownloadOutlined
                              style={{
                                marginRight: '10px',
                              }}
                            />
                            点击下载
                          </div>
                        ),
                        showRemoveIcon: false,
                        showDownloadIcon: true,
                      }}
                      onPreview={async (file: UploadFile) => {
                        setPreviewData({
                          id: file.uid,
                          name: file.name,
                          mimeType: file.mimeType,
                          url: encodeURI(file.url),
                        });
                        setPreviewOpen(true);
                      }}
                    />
                  </>
                )}

                {details?.releaseContent && (
                  <>
                    <Divider
                      orientation="left"
                      style={{
                        fontSize: 14,
                        fontWeight: 'bold',
                      }}
                    >
                      报道要求
                    </Divider>
                    <div
                      dangerouslySetInnerHTML={{
                        __html: `${details?.releaseContent}`,
                      }}
                    />
                  </>
                )}
                {details?.attachments && details?.attachments.length > 0 && (
                  <DrawerForm
                    title={previewData?.name}
                    drawerProps={{
                      width: 900,
                      destroyOnClose: true,
                    }}
                    open={previewOpen}
                    onOpenChange={async (visible) => {
                      if (visible) {
                        if (
                          previewData?.mimeType !== null &&
                          previewData?.mimeType?.indexOf('image') > -1
                        ) {
                          //图片预览
                        } else {
                          setPreviewLoading(true);

                          //   const response = await cuesAttachmentPreview({
                          //     id: previewData?.id,
                          //   });

                          //   if (response.code === 0) {
                          //     setPreviewOnlineUrl(response.data);
                          //   } else {
                          //     message.error('暂时无法预览');
                          //     setPreviewLoading(false);
                          //   }
                        }
                      } else {
                        setPreviewOpen(false);
                        setPreviewData(undefined);
                        setPreviewOnlineUrl(undefined);
                      }
                    }}
                    submitter={{
                      searchConfig: {
                        submitText: '下载',
                      },
                    }}
                    onFinish={async (values) => {
                      window.open(previewData?.url, '_blank');
                    }}
                  >
                    <Alert
                      style={{
                        marginBottom: 20,
                      }}
                      message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                      type="warning"
                      showIcon
                    />
                    {previewData?.mimeType !== null &&
                    previewData?.mimeType?.indexOf('image') > -1 ? (
                      <Image width="100%" src={previewData?.url} />
                    ) : (
                      <Spin spinning={previewLoading}>
                        <iframe
                          ref={iframeRef}
                          src={previewOnlineUrl}
                          height={windowSize.innerHeight - 220}
                          width="100%"
                          frameBorder="0"
                          // scrolling="false"
                          allowFullScreen={true}
                          // scrolling={'no'}
                        />
                      </Spin>
                    )}
                  </DrawerForm>
                )}

                {(access.媒体采访x配置x发布者 || access.媒体采访x配置x接收者) && (
                  <>
                    <Divider
                      orientation="left"
                      style={{
                        fontSize: 14,
                        fontWeight: 'bold',
                      }}
                    >
                      媒体回复
                    </Divider>
                    <ProList<NeedsData.Receipt>
                      style={{
                        marginTop: 10,
                      }}
                      ghost
                      request={async (params = {}) => {
                        const response = await pageReleaseReceipt({
                          ...params,
                          id: details?.id,
                          type: 2,
                        });
                        return Promise.resolve({
                          data: response.data.data,
                          total: response.data.total,
                          success: response.code === 0,
                        });
                      }}
                      actionRef={actionRef}
                      rowKey="id"
                      dateFormatter="string"
                      bordered
                      search={false}
                      sticky
                      pagination={{
                        showQuickJumper: true,
                        showSizeChanger: true,
                        defaultPageSize: 20,
                      }}
                      metas={{
                        title: {
                          dataIndex: 'createdOrganizationName',
                          render: (dom, entity) => {
                            return (
                              <Space size={0}>
                                <Tag color={entity.type === 2 ? '#87d068' : '#1AA15F'}>
                                  {entity.type === 2 ? '已回复' : '已阅读'}
                                </Tag>
                                <Avatar
                                  size="small"
                                  icon={<UserOutlined />}
                                  src={entity.createdOrganizationAvatar}
                                />
                                <span
                                  style={{
                                    marginLeft: '5px',
                                    marginRight: '5px',
                                  }}
                                >
                                  {entity.createdOrganizationName}
                                </span>
                                -
                                <span
                                  style={{
                                    marginLeft: '5px',
                                  }}
                                >
                                  {entity.createdAccountName}
                                </span>
                                {/* {currentUser?.id === entity.createdAccountId && (
                      <UpdateReceipt
                        item={entity}
                        onSave={() => {
                          actionRef.current?.reload();
                        }}
                      />
                    )} */}
                              </Space>
                            );
                          },
                        },
                        description: {
                          dataIndex: 'content',
                          render: (dom, entity) => {
                            return entity.content ? (
                              <div style={{ display: 'flex', alignItems: 'flex-start' }}>
                                <div style={{ width: 65, whiteSpace: 'nowrap' }}>回复内容：</div>
                                <Typography.Paragraph
                                  style={{ flexGrow: 1, margin: 0 }}
                                  type="secondary"
                                  ellipsis={{
                                    rows: 2,
                                    expandable: true,
                                    onEllipsis: (ellipsis) => {
                                      console.log('Ellipsis changed:', ellipsis);
                                    },
                                  }}
                                  copyable
                                >
                                  {entity.content}
                                </Typography.Paragraph>
                              </div>
                            ) : (
                              <></>
                            );
                          },
                        },
                        actions: {
                          render(dom, entity, index, action, schema) {
                            return <a>{entity.createdTime}</a>;
                          },
                        },
                      }}
                      toolbar={{}}
                      toolBarRender={false}
                    />
                  </>
                )}
              </>
            )}
          </Col>

          {approvals && (
            <Col span={access.媒体采访x配置x管理员 ? 9 : 0}>
              {details?.isRelease == 1 && (
                <Descriptions>
                  <Descriptions.Item label="阅读和回复">
                    <ReceiptNeeds interviewId={details?.id} onRefurbish={function (): void {}} />
                  </Descriptions.Item>
                </Descriptions>
              )}
              <ProList
                ghost
                rowKey="id"
                headerTitle="请示列表"
                dataSource={approvals}
                showActions="hover"
                metas={{
                  title: {
                    dataIndex: 'approvalCombineName',
                    render: (text, row, index, action) => {
                      return (
                        <Flex justify={'space-between'} align={'center'}>
                          <Tag
                            color={
                              row.isApproval == null
                                ? 'orange'
                                : row.isApproval == 1
                                ? '#87d068'
                                : '#f50'
                            }
                          >
                            {row.isApproval == null
                              ? '审批中'
                              : row.isApproval == 1
                              ? '通过'
                              : '驳回'}
                          </Tag>
                          <span>
                            {row.askCombineName} -&gt; {row.approvalCombineName}
                          </span>
                        </Flex>
                      );
                    },
                  },
                  subTitle: {
                    dataIndex: 'labels',
                    render: (_, row) => {
                      return <Space size={0}></Space>;
                    },
                    search: false,
                  },
                  description: {
                    render: (text, row, index, action) => {
                      return (
                        <>
                          {row.approvalContent != null && (
                            <>
                              <Space>
                                <span>{row.approvalTime}</span>
                              </Space>
                              <Typography.Paragraph>
                                <blockquote>{row.approvalContent}</blockquote>
                              </Typography.Paragraph>
                            </>
                          )}
                          <Space>
                            {/* <span>请示：{row.askCombineName}</span> */}
                            <span>{row.createdTime}</span>
                          </Space>
                          <Typography.Paragraph>
                            <blockquote>{row.askContent}</blockquote>
                          </Typography.Paragraph>
                        </>
                      );
                    },
                  },
                  actions: {
                    render: (text, row) => [
                      row.isNeedReply == 1 ? (
                        <AddApproval
                          id={row.id}
                          onRefurbish={function (): void {
                            loadListApprovalAsk();
                          }}
                        />
                      ) : (
                        <></>
                      ),
                    ],
                    search: false,
                  },
                }}
              />
            </Col>
          )}
        </Row>
      </Spin>
    </DrawerForm>
  );
};

export default DetailsNeeds;
